package com.example.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.controller.vo.EvaluationsVo;
import com.example.controller.vo.Result;
import com.example.entity.Evaluations;
import com.example.entity.PageView;
import com.example.service.IEvaluationsService;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author yzy
 * @since 2025-08-04
 */
@RestController
@RequestMapping("/evaluations")
public class EvaluationsController {

    @Autowired
    private IEvaluationsService iEvaluationsService;
    @Autowired
    private IUserService iuserService;

    /**
     * 分页查询评论（联表查询用户名、头像等）
     */
    @GetMapping("/list")
    public Result list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "productName", required = false) String productName,
            @RequestParam(value = "userName", required = false) String userName
    ) {
        // 调用服务层联表分页查询
        IPage<EvaluationsVo> pageResult = iEvaluationsService.selectEvalVoPage(pageNum, pageSize, productName, userName);

        // 封装分页视图对象
        PageView pageView = new PageView();
        pageView.setPageNum((int) pageResult.getCurrent());
        pageView.setPageSize((int) pageResult.getSize());
        pageView.setAllRow(pageResult.getTotal());
        pageView.setTotalPage(pageResult.getPages());
        pageView.setData(pageResult.getRecords());  // 数据为EvaluationsVo列表

        return Result.success(pageView);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") int id) {
        iEvaluationsService.removeById(id);
        return Result.success("删除成功");
    }

    @RequestMapping("/comList")
    public Result comList(@RequestParam(value = "productId") Integer productId){
        List<EvaluationsVo> list = iEvaluationsService.listTree(productId);
        return Result.success(list);
    }

    @RequestMapping("/save")
    public Result save(@RequestBody Evaluations evaluations) {
        // 1. 基础参数校验
        if (evaluations.getCommenterId() == null) {
            return Result.failed("评论者ID不能为空");
        }
        if (StringUtils.isEmpty(evaluations.getContent())) {
            return Result.failed("评论内容不能为空");
        }
        if (evaluations.getProductId() == null) {
            return Result.failed("关联商品ID不能为空");
        }
        if (StringUtils.isEmpty(evaluations.getContentType())) {
            return Result.failed("内容类型不能为空（如：product）");
        }

        // 2. 处理评论层级关系（通过fatherId区分一级评论和回复）
        Integer fatherId = evaluations.getFatherId();
        if (fatherId == null) {
            // 默认为一级评论（无父评论）
            evaluations.setFatherId(0);
        } else if (fatherId > 0) {
            // 回复评论：验证父评论是否存在且属于同一商品
            Evaluations parentEval = iEvaluationsService.getById(fatherId);
            if (parentEval == null) {
                return Result.failed("回复的评论不存在");
            }
            // 确保回复与原评论属于同一商品
            if (!parentEval.getProductId().equals(evaluations.getProductId())) {
                return Result.failed("不能跨商品回复评论");
            }
        }

        // 3. 补充默认字段
        evaluations.setCreateTime(LocalDateTime.now());
        // 初始化点赞数（避免null）
        if (evaluations.getUpvoteList() == null) {
            evaluations.setUpvoteList(0);
        }
          evaluations.setContentType("product");
        // 4. 保存评论（新增或更新）
        boolean success = iEvaluationsService.saveOrUpdate(evaluations);
        if (success) {
            // 5. 操作完成
            //Evaluations saved = iEvaluationsService.getById(evaluations.getId());
            return Result.success("操作成功");
        } else {
            return Result.failed("评论保存失败，请重试");
        }
    }


}
